import 'package:flutter/material.dart';
import '../config/config_loader.dart';
import '../config/user_config.dart';

class ServerConfigPage extends StatefulWidget {
  const ServerConfigPage({Key? key}) : super(key: key);

  @override
  _ServerConfigPageState createState() => _ServerConfigPageState();
}

class _ServerConfigPageState extends State<ServerConfigPage> {
  final _formKey = GlobalKey<FormState>();
  final ConfigLoader _configLoader = ConfigLoader();
  late bool _useCustomConfig;

  // API配置控制器
  final _apiHostController = TextEditingController();
  final _apiPortController = TextEditingController();
  final _apiProtocolController = TextEditingController();
  final _apiPathPrefixController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _useCustomConfig = _configLoader.userConfig.isEnabled;
    _loadCurrentConfig();
  }

  void _loadCurrentConfig() {
    final apiConfig = _configLoader.apiConfig;

    // 加载API配置
    _apiHostController.text = apiConfig['host'] ?? '';
    _apiPortController.text = apiConfig['port']?.toString() ?? '';
    _apiProtocolController.text = apiConfig['protocol'] ?? '';
    _apiPathPrefixController.text = apiConfig['path_prefix'] ?? '';
  }

  @override
  void dispose() {
    _apiHostController.dispose();
    _apiPortController.dispose();
    _apiProtocolController.dispose();
    _apiPathPrefixController.dispose();
    super.dispose();
  }

  Future<void> _saveConfig() async {
    if (!_formKey.currentState!.validate()) return;

    if (_useCustomConfig) {
      // 保存API配置
      final apiConfig = {
        'host': _apiHostController.text,
        'port': int.parse(_apiPortController.text),
        'protocol': _apiProtocolController.text,
        'path_prefix': _apiPathPrefixController.text,
      };

      await _configLoader.userConfig.setApiConfig(apiConfig);
    } else {
      await _configLoader.userConfig.clear();
    }

    await _configLoader.userConfig.setEnabled(_useCustomConfig);

    if (mounted) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('配置已保存')));
      Navigator.of(context).pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('服务器配置'),
        actions: [
          IconButton(icon: const Icon(Icons.save), onPressed: _saveConfig),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SwitchListTile(
                title: const Text('使用自定义服务器配置'),
                value: _useCustomConfig,
                onChanged: (value) {
                  setState(() {
                    _useCustomConfig = value;
                  });
                },
              ),
              if (_useCustomConfig) ...[
                const SizedBox(height: 16),
                const Text(
                  'API服务器配置',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 8),
                TextFormField(
                  controller: _apiHostController,
                  decoration: const InputDecoration(
                    labelText: '主机地址',
                    hintText: '例如: api.example.com',
                  ),
                  validator: (value) {
                    if (value?.isEmpty ?? true) return '请输入主机地址';
                    return null;
                  },
                ),
                TextFormField(
                  controller: _apiPortController,
                  decoration: const InputDecoration(
                    labelText: '端口',
                    hintText: '例如: 8000',
                  ),
                  keyboardType: TextInputType.number,
                  validator: (value) {
                    if (value?.isEmpty ?? true) return '请输入端口号';
                    final port = int.tryParse(value!);
                    if (port == null || port <= 0 || port > 65535) {
                      return '请输入有效的端口号(1-65535)';
                    }
                    return null;
                  },
                ),
                TextFormField(
                  controller: _apiProtocolController,
                  decoration: const InputDecoration(
                    labelText: '协议',
                    hintText: '例如: http 或 https',
                  ),
                  validator: (value) {
                    if (value?.isEmpty ?? true) return '请输入协议';
                    if (value != 'http' && value != 'https') {
                      return '协议必须是 http 或 https';
                    }
                    return null;
                  },
                ),
                TextFormField(
                  controller: _apiPathPrefixController,
                  decoration: const InputDecoration(
                    labelText: 'API路径前缀',
                    hintText: '例如: /api',
                  ),
                  validator: (value) {
                    if (value?.isEmpty ?? true) return '请输入API路径前缀';
                    if (!value!.startsWith('/')) {
                      return 'API路径前缀必须以/开头';
                    }
                    return null;
                  },
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }
}
